package io.renren.common.exception;

import cn.hutool.core.map.MapUtil;
import com.mysql.cj.jdbc.exceptions.MysqlDataTruncation;
import io.renren.common.utils.*;
import io.renren.modules.log.entity.SysLogErrorEntity;
import io.renren.modules.log.service.SysLogErrorService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLSyntaxErrorException;
import java.util.Map;


/**
 * 异常处理器
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0
 */
@Slf4j
@RestControllerAdvice
@AllArgsConstructor
public class RenExceptionHandler {
    private final SysLogErrorService sysLogErrorService;

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(RenException.class)
    public Result<Object> handleRenException(RenException ex) {
        return new Result<>().error(ex.getCode(), ex.getMsg());
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result<Object> handleDuplicateKeyException(DuplicateKeyException ex) {
        log.error(ex.getMessage(), ex);
        return new Result<>().error(ErrorCode.DB_RECORD_EXISTS);
    }

    @ExceptionHandler(AuthorizationException.class)
    public Result<Object> handleAuthorizationException(AuthorizationException e) {
        log.error(e.getMessage(), e);
        return new Result<>().error("没有权限，请联系管理员授权");
    }

    @ExceptionHandler(DataIntegrityViolationException.class)
    public Result<Object> dataIntegrityViolationException(DataIntegrityViolationException e) {
        // 异常信息类
        Throwable cause = e.getCause();
        log.error(e.getMessage(), e);
        // 字段超长
        if (cause.getClass().equals(MysqlDataTruncation.class)) {
            return new Result<>().error("输入的内容超过数据库配置的长度，请联系管理员");
            // 数据库插入记录异常,联合索引冲突
        } else if (cause.getClass().equals(SQLIntegrityConstraintViolationException.class)) {
            return new Result<>().error("唯一索引冲突");
            // 数据库插入异常
        } else if (cause.getClass().equals(SQLSyntaxErrorException.class)) {
            return new Result<>().error("数据库插入异常");
        }
        return new Result<>().error("数据库操作异常");
    }

    @ExceptionHandler(Exception.class)
    public Result<Object> handleException(Exception ex) {
        log.error(ex.getMessage(), ex);

        saveLog(ex);

        return new Result<>().error();
    }

    /**
     * 保存异常日志
     */
    private void saveLog(Exception ex) {
        SysLogErrorEntity log = new SysLogErrorEntity();

        //请求相关信息
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        if (null != request) {
            log.setIp(IpUtils.getIpAddr(request));
            log.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
            log.setRequestUri(request.getRequestURI());
            log.setRequestMethod(request.getMethod());
            Map<String, String> params = HttpContextUtils.getParameterMap(request);
            if (MapUtil.isNotEmpty(params)) {
                log.setRequestParams(JsonUtils.toJsonString(params));
            }
        }

        //异常信息
        log.setErrorInfo(ExceptionUtils.getErrorStackTrace(ex));

        //保存
        sysLogErrorService.save(log);
    }
}
